// 发布订阅模式
export default class PubSub<T extends string> {
  private events: Record<T, Function[]> = {} as Record<T, Function[]>

  subscribe(event: T, callback: Function) {
    if (!this.events[event]) {
      this.events[event] = []
    }
    this.events[event].push(callback)

    return () => {
      this.unsubscribe(event, callback)
    }
  }

  publish(event: T, data: any) {
    if (!this.events[event]) {
      return []
    }
    return this.events[event].map(callback => callback(data))
  }

  unsubscribe(event: T, callback?: Function) {
    if (!this.events[event]) {
      return
    }
    if (!callback) {
      this.events[event] = []
      return
    }

    this.events[event] = this.events[event].filter(subscriber => subscriber !== callback)
  }
}
